/**
 * Copyright (c) 2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

var InPlaceEditor = new Class(
{
	Implements:     Options,
	Binds:          ['save', 'start', 'afterSave'],
	BindsWithEvent: ['onEdit', 'onSave', 'onCancel', 'onEscape'],
	
	editable: null,
	content:  null,
	button:   null,
	wrapper:  null,
	form:     null,
	url:      null,
	
	initialize: function(editable)
	{
		this.editable = $(editable);
		this.content  = this.editable.getElement('.editable-content');
		this.button   = this.editable.getElement('.editable-button');
		
		if (this.button)
		{
			this.url = this.button.get('href');
			this.button.addEvent('click', this.onEdit);
		}
	},
	
	onEdit: function(evt)
	{
		evt.stop();
		
		// fetches and displays form
		this.wrapper = this.editable.clone()
			.empty()
			.set({
				'id': '',
				'load': {
					'method': 'get',
					'onComplete': this.start
				},
				'events': {
					'outerclick': this.save
				}
			})
			.inject(this.editable, 'after')
			.load(this.url);
		
		// hides editable area
		this.editable.set({
			'styles': {
				'display': 'none',
				'visibility': 'hidden'
			}
		});
	},
	
	start: function()
	{
		this.form    = this.wrapper.getElement('form');
		var cancel   = this.wrapper.getElement('.cancel');
		var textarea = this.form.getElement('textarea');
		
		this.form.addEvent('submit', this.onSave);
		cancel.addEvent('click', this.onCancel);
		textarea.addEvent('keypress', this.onEscape);
		
		if (textarea.hasClass('auto-resize') && Textarea && Textarea.AutoResize) {
			new Textarea.AutoResize(textarea);
		}
		/*if (textarea.getAttribute('maxlength') && Textarea && Textarea.Maxlength) {
			new Textarea.Maxlength(textarea);
		}*/
	},
	
	onSave: function(evt)
	{
		evt.stop();
		this.save();
	},
	
	save: function(evt)
	{
		new Request({
			'url': this.url,
			'onComplete': this.afterSave
		}).post(this.form);
	},
	
	afterSave: function(html)
	{
		this.content.set({'html': html});
		this.stop();
	},
	
	onCancel: function(evt)
	{
		evt.stop();
		this.stop();
	},
	
	onEscape: function(evt)
	{
		if (evt.key == 'esc') {
			this.stop();
		}
		else if (evt.control && !evt.shift && !evt.alt && !evt.meta && evt.key == 'enter') {
			this.save();
		}
	},
	
	stop: function()
	{
		this.wrapper.removeEvent('outerclick', this.save);
		this.wrapper.destroy();
		this.editable.set({
			'styles': {
				'display':    '',
				'visibility': ''
			}
		});
	}
});

window.addEvent('domready', function()
{
	$$('.editable').each(function(editable) {
		new InPlaceEditor(editable);
	});
});
